<?php

namespace App\Http\Controllers\Guard\Advert;

use App\Http\Controllers\Common\ApiController;
use App\Models\Advert\AdvertChannel;
use Illuminate\Http\Request;

class ChannelController extends ApiController{

    private $model = AdvertChannel::class;

    public function lst(Request $request) {

        if($request->has('tree')){
            $conditions = ['pid'=>0];
            $conditions['orderBy']['col'] = 'id';
            $conditions['orderBy']['sort'] = 'asc';
            $records = (new $this->model())->getLst($conditions)->with('children')->get($this->getCol);
            $this->handleChildren($records);
            return responseSuccess($records->toArray());
        }
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);
        $conditions = $request->input();
        $records = (new $this->model())->getLst($conditions)->paginate($pageSize,$this->getCol,'page',$page);
        $mapChannel = (new $this->model())->pluck('name','id')->toArray();
        foreach ($records as $record) {
            $record->p_name = $mapChannel[$record->pid]??'顶级频道';
        }

        return responseSuccess($records->items(),$records->total());

    }

    public function add(Request $request) {
        $info = $request->input();

        $this->validate($request, [
            'name'=>'required|min:1|max:20'
        ],[],[
            'name'=>'频道名称'
        ]);
        //dd($info);

        $this->model::updateOrCreate(['id'=>$info['id']??0],$info);
        return responseSuccess();
    }

    public function detail(Request $request){
        $id = $request->input('id',0);
        $records = $this->getDetail($this->model,[$id]);
        foreach ($records as $record) {
            $record->p_name = $record->getParent()->name??'顶级频道';
        }
        return responseSuccess($records->toArray(),1);
    }

    public function change(Request $request) {
        $ids = $request->input('ids',[]);
        $status = $request->input('status');
        return $this->changeColByIds($this->model, [$ids],compact('status'));
    }

    public function del(Request $request) {
        $ids = $request->input('ids',[]);
        return $this->delRecords($this->model, $ids);
    }
}
